/**
 * Created by way on 16/9/19.
 * 调用后台api接口
 * 所有调用需要 token 身份, 如没有则自动获取, 并保存到 sessionStorage
 */

import * as ajax from '../lib/kajax';
import cfg from '../config';
import {urlParam} from '../lib/kutil';


export function mobile(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.mobile, val);
  else {
    return sessionStorage.getItem(cfg.app.mobile) || '';
  }
}
export function sid(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.sid, val);
  else {
    return sessionStorage.getItem(cfg.app.sid) || '';
  }
}
export function tab(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.tab, val);
  else {
    return sessionStorage.getItem(cfg.app.tab) || '';
  }
}

export function token(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.token, val);
  else {
    return cfg.dev.token ? cfg.dev.token : sessionStorage.getItem(cfg.app.token) || '';
  }
}

export function code(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.code, val);
  else {
    return sessionStorage.getItem(cfg.app.code) || '';
  }
}

export function lastCode(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.lastCode, val);
  else {
    return sessionStorage.getItem(cfg.app.lastCode) || '';
  }
}

export function docker(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.docker, val);
  else {
    return sessionStorage.getItem(cfg.app.docker) || 'wx';
  }
}

export function host() {
  return docker() === 'rel' ? cfg.rel.host : cfg.api.host;
}

/**
 * 通过mobile 获取 token
 * @param cb
 */
export function getToken(cb) {
  if (token())
    cb(null, token());
  else {
    if (mobile()) {
      ajax.get(`${HOST_URL}${cfg.ogs.token}`, `mobile=${mobile()}&tab=${tab()}&sid=${sid()}`, (rs) => {
        console.log(`getToken rs:${rs}`);
        if (rs) {
          const r = JSON.parse(rs);
          if (r.rc === 200) {
            token(r.token);
            cb(null, r);
          } else
            cb(new Error('获取身份失败,请退出重新进入或联系客服!'), '');
        }
      });
    } else
      cb(new Error('获取身份失败,请退出重新进入或联系客服!'), '');
  }
}

/**
 * get
 * @param url
 * @param param [&=...]
 * @param cb
 */
export function get(url, param, cb) {
  console.log('token   ', token());
  if (token()) {
    param = param ? `${param}&token=${token()}` : `token=${token()}`;
    ajax.get(url, param, cb);
  } else {
    getToken((err, rs) => {
      param = param ? `${param}&token=${rs.token}` : `token=${rs.token}`;
      ajax.get(url, param, cb);
    });
  }
}
/**
 * post
 * @param url
 * @param param [obj][&=...]
 * @param cb
 */
export function post(url, param, cb) {
  if (token()) {
    if (param instanceof Object)
      param.token = token();
    else
      param = param ? `${param}&token=${token()}` : `token=${token()}`;
    ajax.post(url, param, cb);
  } else {
    getToken((err, tok) => {
      if (param instanceof Object)
        param.token = tok;
      else
        param = param ? `${param}&token=${tok}` : `token=${tok}`;
      ajax.post(url, param, cb);
    });
  }
}


export function getView(url, param, cb) {
  // alert(`url:${url} para:${para}`);
  ajax.get((url.indexOf('http://') === -1 && url.indexOf('https://') === -1)
    ? `${cfg.view.host}${url}` : url, param, cb);
}

export function getDoc(url, param, cb) {
  // alert(`url:${url} para:${para}`);
  ajax.get((url.indexOf('http://') === -1 && url.indexOf('https://') === -1)
    ? `${cfg.doc.host}${url}` : url, param, cb);
}
export function postForm(url, data, cb) {
  if (token()) {
    data.append('token', token());
    ajax.postForm(url.indexOf(host()) === -1 ? `${host()}${url}` : url, data, cb);
  } else {
    if (/rel.nuoyadalu.com/.test(url))
      docker('rel');
    getToken((err, tk) => {
      data.append('token', tk);
      ajax.postForm(url.indexOf(host()) === -1 ? `${host()}${url}` : url, data, cb);
    });
  }
}

/**
 * 从服务器获取微信上传签名、时标
 * @param type
 * @returns {string}
 */
export function getWxSign(cb) {
  let href = `url=${location.href}`;
  href = href.replace(/&/, '%26');
  href = href.replace(/#[\s\S]*$/, '');
  ajax.get(`${cfg.api.host}${cfg.api.wxsign}`, href, rs => {
    cb(JSON.parse(rs));
  });
}

export function getUser(url, param, cb) {
  get(url, param, (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      if (r.rc == 200) {
        if (cb) cb(r.relInfoRes);
      } else
        alert('获取身份失败,请退出重新进入或联系客服!');
    } else {
      alert('获取身份失败,请退出重新进入或联系客服!');
    }
  });
}